import * as THREE from "three";

const partitionShaderBeforeCompileCb = (height, colorCss, opacity) => {
  const color = new THREE.Color().setStyle(colorCss);
  return (shader) => {
    shader.uniforms.iTime = {value: 0.0};
    shader.uniforms.partitionHeight = {value: height};
    shader.uniforms.opacityColor = {value: new THREE.Vector4(color.r, color.g, color.b, opacity)};

    let token = '#define STANDARD';
    let insert = /* glsl */`
    varying float zVal;
					`;
    shader.vertexShader = shader.vertexShader.replace( token, token + insert );

    token = 'void main() {'
    insert = /* glsl */`
  void main() {
    vec4 worldPos = modelMatrix * vec4(position, 1.0);
    zVal = worldPos.z;
					`;
    shader.vertexShader = shader.vertexShader.replace( token, insert );

    token = '#define STANDARD';
    insert = /* glsl */`
    uniform float iTime;
    uniform float partitionHeight;
    uniform vec4 opacityColor;
    varying float zVal;
					`;
    shader.fragmentShader = shader.fragmentShader.replace( token, token + insert );
    token = 'void main() {';
    insert = /* glsl */`
    void main() {
      if (zVal >= partitionHeight) {
        gl_FragColor = opacityColor;
        return;
      }
					`;
    shader.fragmentShader = shader.fragmentShader.replace( token, insert );
  }
}

export {partitionShaderBeforeCompileCb}
